import org.junit.Test;

import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * 调用Collections.sort()方法，通过定制排序比较两个Employee（先按年龄比，年龄相同按姓名比），使用Lambda作为参数传递。
 */
public class TestLambda {
    List<Employee> emps = Arrays.asList(
            new Employee("张三", 18, 9999.99),
            new Employee("李四", 59, 5555.99),
            new Employee("王五", 28, 6666.99),
            new Employee("赵六", 8, 3333.99),
            new Employee("田七", 38, 7777.99)
    );

    /**
     * Lambda表达式实现
     */
    @Test
    public void test1() {
        Collections.sort(emps, (e1, e2) -> {
            if (e1.getAge() == e2.getAge()) {
                return e1.getName().compareTo(e2.getName());
            } else {
                return Integer.compare(e1.getAge(), e2.getAge());
            }
        });

        for (Employee emp: emps) {
            System.out.println(emp);
        }
    }

    /**
     * 匿名类实现
     */
    @Test
    public void test2() {
        Collections.sort(emps, new Comparator<Employee>() {
            @Override
            public int compare(Employee e1, Employee e2) {
                if (e1.getAge() == e2.getAge()) {
                    return e1.getName().compareTo(e2.getName());
                } else {
                    return Integer.compare(e1.getAge(), e2.getAge());
                }
            }
        });

        for (Employee emp: emps) {
            System.out.println(emp);
        }
    }

    @Test
    public void test3() {
        String trimStr = strHandle("\t\t\t我大尚硅谷威武  ", (str) -> str.trim());
        System.out.println(trimStr);

        String upper = strHandle("\t\t\t我大尚硅谷威武  ", (str) -> str.toUpperCase());
        System.out.println(upper);
    }

    // 需求：用于处理字符串
    public String strHandle(String str, MyFunction mf) {
        return mf.getValue(str);
    }

    //匿名类方式
    @Test
    public void test5() {
        op(100L, 200L, new MyFunction2<Long, Long>() {
            @Override
            public Long getValue(Long t1, Long t2) {
                return t1 + t2;
            }
        });
    }
    // Lambda方式
    @Test
    public void test4() {
        op(100L, 200L, (x,y) -> x + y);
        op(100L, 200L, (x,y) -> x * y);
    }

    //需求：对于两个Long型数据进行处理
    public void op(Long l1, Long l2, MyFunction2<Long, Long> mf) {
        System.out.println(mf.getValue(l1, l2));
    }

}
